package com.example.wwk.graduationpractice.SmackUtils;




import org.jivesoftware.smack.AbstractXMPPConnection;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import java.io.IOException;


/**
 * Created by wwk on 2017/3/14.
 * 用以XMPP连接服务器
 */

public class XmppConnectUtils {
    //静态工厂，用以创建实例
    private static final String computerIp="192.168.191.1";
    private static final String telePhoneIp="172.20.10.8";
    private static AbstractXMPPConnection connection = null;
    private static String SERVER_IP =computerIp ;       //服务器IP地址
    private static int PORT = 5222;                       //服务器端口
    private static String SERVER_NAME =computerIp ;      //服务器名称


    private static void openConnection() {

        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
        config.setHost(SERVER_IP);//服务器IP地址
        config.setPort(PORT); //服务器端口
        config.setServiceName(SERVER_NAME);  //服务器名称
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); //是否开启安全模式
        config.setConnectTimeout(20000);
        config.setSendPresence(false);
//            config.setCompressionEnabled(false);//是否开启压缩
//            config.setDebuggerEnabled(true); //开启调试模式

        connection = new XMPPTCPConnection(config.build());
        try {

            connection.connect();           //连接服务器
        } catch (SmackException | IOException | XMPPException e) {

            e.printStackTrace();
        }

    }

    public static AbstractXMPPConnection getConnection() {
        if (connection == null || !connection.isConnected()) {
            openConnection();
        }
        return connection;
    }

    public static void  closeConnection(){
        Presence presence = new Presence(Presence.Type.unavailable);
        try {
            connection.disconnect(presence);
            connection =null;
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }

    }
}
